// source: http://blog.thematicmapping.org/2008/04/openlayers-and-google-chart-mashup.html
var map, wms, vectors;

function z(s) {
	return s == '' ? '0' : s; 
}

function full(s) {
	return s + '% completed'; 
}

function n(s) {
	return parseInt(z(s));
}

function total(feature) {
	return n(feature.attributes["Yes"]) + n(feature.attributes["No"]) + n(feature.attributes["N/A"]);
}

function gc_values(feature) {
	return z(feature.attributes["Yes"]) + ',' + z(feature.attributes["No"]);
}

function bar_values(feature) {
	return feature.attributes["Strategy 1 Yes"] + ',' + feature.attributes["Strategy 2 Yes"] + ',' + feature.attributes["Strategy 3 Yes"] +',' +feature.attributes["Strategy 4 Yes"] + ',' + feature.attributes["Strategy 5 Yes"] + ',' + feature.attributes["Strategy 6 Yes"] +',' + feature.attributes["Strategy 7 Yes"] + '|' + feature.attributes["Strategy 1 No"] + ',' + feature.attributes["Strategy 2 No"] +','+ feature.attributes["Strategy 3 No"] + ',' + feature.attributes["Strategy 4 No"] + ',' + feature.attributes["Strategy 5 N/A"] +','+ feature.attributes["Strategy 6 No"] + ',' + feature.attributes["Strategy 7 No"] + '|' + feature.attributes["Strategy 1 N/A"] +',' + feature.attributes["Strategy 2 N/A"] + ',' + feature.attributes["Strategy 3 N/A"] + ',' + feature.attributes["Strategy 4 N/A"] +',' +feature.attributes["Strategy 5 N/A"] + ',' + feature.attributes["Strategy 6 N/A"] + ',' + feature.attributes["Strategy 7 N/A"];
}

function gc_values_completness(feature) {
	return z(feature.attributes["name"]) + '|' +' ' +'|' +' ' + '|' +full(feature.attributes["Completeness"]);
}

function desc(feature, field) {
	return field + ": " + (feature.attributes[field] == '' ? '-': feature.attributes[field]);
}

function descAll(feature) {
	return desc(feature, "Yes") + ', ' + desc(feature, "No");
}

function init(){
    var lon = 104;
    var lat = 15.3;
    var zoom = 5;
    var symbol = new Geometry('circle', 20, 1312978855);

    var context = {
        getSize: function(feature) {
            return 30;
        },
        getChartURL: function(feature) {
            var values = gc_values(feature);
			var size = 150;
			if(values == "0,0"){
				var charturl ="/images/attention.png"
			}else{
				var charturl = 'http://chart.apis.google.com/chart?cht=p&chd=t:' + values +'&chco=00ff00,ff0000'+ '&chs=' + size + 'x' + size + '&chf=bg,s,ffffff00';
			}
			return charturl;
        }
    };
	
	 var context_bar = {
        getSize: function(feature) {
            return 50;
        },
        getChartURL: function(feature) {
            var values = bar_values(feature);
			var total_val = total(feature);
            var size = 250;
            var charturl = 'http://chart.apis.google.com//chart?cht=bhs&chd=t:'+values+'&chco=00FF00,FF0000,575757&chf=bg,s,00000000&chs='+ size +'&chds=0,6';
			return charturl;
        }
    };
	
	 var context_completness = {
        getSize: function(feature) {
            return 80;
        },
        getChartURL: function(feature) {
            var values = gc_values_completness(feature);
            var size = 50;
            var charturl = 'http://chart.apis.google.com//chart?chst=d_fnote_title&chld=sticky_y|1|004400|l|' + values + '&chd=t:' + values;
			return charturl;
        }
    };

    var template = {
        fillOpacity: 1.0,
        externalGraphic: "${getChartURL}",
        graphicWidth: "${getSize}",
        graphicHeight: "${getSize}",
        strokeWidth: 0
    };

    var style = new OpenLayers.Style(template, {context: context});
	var styleMap = new OpenLayers.StyleMap({'default': style, 'select': {fillOpacity: 0.7}});
	
	var style_bar = new OpenLayers.Style(template, {context: context_bar});
	var styleMap_bar = new OpenLayers.StyleMap({'default': style_bar, 'select': {fillOpacity: 0.7}});
	
	var style_completness = new OpenLayers.Style(template, {context: context_completness});
	var styleMap_completness = new OpenLayers.StyleMap({'default': style_completness, 'select': {fillOpacity: 0.7}});

    var options = {
        numZoomLevels: 10,
        controls: []  // Remove all controls
    };

    map = new OpenLayers.Map( 'map', options );
	
	map.addControl(new OpenLayers.Control.Navigation());

	
	map.addControl(new OpenLayers.Control.LayerSwitcher({'div':OpenLayers.Util.getElement('layerswitcher')}));

    wms  = new OpenLayers.Layer.Google(
                "Google Physical",
                {type: G_PHYSICAL_MAP}
            );
			
	var gmap = new OpenLayers.Layer.Google(
                "Google Streets",
                {numZoomLevels: 20,
				"sphericalMercator": true}
            );
    var ghyb = new OpenLayers.Layer.Google(
                "Google Hybrid",
                {type: G_HYBRID_MAP, numZoomLevels: 20,
				"sphericalMercator": true}
            );
    var gsat = new OpenLayers.Layer.Google(
                "Google Satellite",
                {type: G_SATELLITE_MAP, numZoomLevels: 22,
				"sphericalMercator": true}
            );

									
	dm_wms = new OpenLayers.Layer.GML( "Percentage completed", '/users/map_data',
										{ format: OpenLayers.Format.GeoJSON,
                                          styleMap: styleMap_completness,
                                          isBaseLayer: false,
                                          projection: new OpenLayers.Projection("EPSG:4326")} );

    vectors = new OpenLayers.Layer.GML( "Yes/No Pie Charts", "/users/map_data",
                                        { format: OpenLayers.Format.GeoJSON,
                                          styleMap: styleMap,
                                          isBaseLayer: false,
                                          projection: new OpenLayers.Projection("EPSG:4326")} );
										  
	bar_layer = new OpenLayers.Layer.GML( "Bar Charts", "/users/map_data_strategy",
                                        { format: OpenLayers.Format.GeoJSON,
                                          styleMap: styleMap_bar,
                                          isBaseLayer: false,
                                          projection: new OpenLayers.Projection("EPSG:4326")} );
									
	bar_layer.setVisibility(false);

	map.addLayers([wms, gmap, ghyb, gsat]);


	map.addLayers([wms, dm_wms]);
	
	map.addLayers([wms,bar_layer]);

    map.addLayers([wms, vectors]);

    map.setCenter(new OpenLayers.LonLat(lon, lat), zoom);


    map.addControl(new OpenLayers.Control.LayerSwitcher());
    map.addControl(new OpenLayers.Control.MouseDefaults());
    map.addControl(new OpenLayers.Control.PanZoomBar());

    var options = {
       hover: true,
       onSelect: serialize
    };
	
	var options_completness = {
       hover: true,
       onSelect: serialize_completness 
    };
	
	var options_bar = {
       hover: true,
       onSelect: serialize_bar 
    };

    var select = new OpenLayers.Control.SelectFeature(vectors, options);
    map.addControl(select);
    select.activate();
	
	var select_bar = new OpenLayers.Control.SelectFeature(bar_layer, options_bar);
    map.addControl(select_bar);
    select_bar.activate();
	
	var select_completness = new OpenLayers.Control.SelectFeature(dm_wms, options_completness);
    map.addControl(select_completness);
    select_completness.activate();
}

function serialize_completness() {
    var Msg = "<strong>" + dm_wms.selectedFeatures[0].attributes["name"] + "</strong> ";
    Msg    += descAll(dm_wms.selectedFeatures[0]);
	Msg    += "<strong> Completed:  </strong>"+ dm_wms.selectedFeatures[0].attributes["Completeness"] + " %";
    document.getElementById("info").innerHTML = Msg;
}

function serialize() {
    var Msg = "<strong>" + vectors.selectedFeatures[0].attributes["name"] + "</strong> ";
    Msg    += descAll(vectors.selectedFeatures[0]);
	Msg    += "<strong> Completed:  </strong>"+ vectors.selectedFeatures[0].attributes["Completeness"] + " %";
    document.getElementById("info").innerHTML = Msg;
}

function serialize_bar() {
    var Msg = "<strong>" + bar_layer.selectedFeatures[0].attributes["name"] + "</strong> ";
    Msg    += descAll(bar_layer.selectedFeatures[0]);
	Msg    += ", N/A: "+ bar_layer.selectedFeatures[0].attributes["N/A"];
	Msg    += "<strong> Completed:  </strong>"+ bar_layer.selectedFeatures[0].attributes["Completeness"] + " %";
    document.getElementById("info").innerHTML = Msg;
}

function Geometry(symbol, maxSize, maxValue){
this.symbol = symbol;
this.maxSize = maxSize;
this.maxValue = maxValue;

this.getSize = function(value){
  switch(this.symbol) {
      case 'circle': // Returns radius of the circle
      case 'square': // Returns length of a side
          return Math.sqrt(value/this.maxValue)*this.maxSize;
      case 'bar': // Returns height of the bar
          return (value/this.maxValue)*this.maxSize;
      case 'sphere': // Returns radius of the sphere
      case 'cube': // Returns length of a side
          return Math.pow(value/this.maxValue, 1/3)*this.maxSize;
  }
}
}		
